package com.grf.rocketmq;

import java.io.UnsupportedEncodingException;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

/**
 * @author : guorf
 * @version : v1.0
 * @description : TODO 顺序消息
 * @createTime : 2023/9/13 11:17
 */
public class OrderMessageProducer {

    /**
     * @description TODO 顺序消息
     * @param args
     **/
    public static void main(String[] args) {
        try {
            DefaultMQProducer producer = ProducerUtil.start();

            String[] tags = new String[] {"TagA", "TagB", "TagC", "TagD", "TagE"};
            for (int i = 0; i < 100; i++) {
                int orderId = i % 10;
                Message msg =
                        new Message(ProducerUtil.TOPIC, tags[i % tags.length], "KEY" + i,
                                ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
                SendResult sendResult = producer.send(msg, (mqs, msg1, arg) -> {
                    Integer id = (Integer) arg;
                    int index = id % mqs.size();
                    return mqs.get(index);
                }, orderId);

                System.out.printf("%s%n", sendResult);
            }

            ProducerUtil.shutdown(producer);
        } catch (MQClientException | RemotingException | MQBrokerException | InterruptedException |
                 UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


}
